<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <style>
        #my_txt {
            width: 100%;
            height: 200px;

        }
    </style>

</head>

<body>


    <div class="contanier">
        <div class="panel panel-default one">
            <div class="panel-body">
                <textarea name="" id="my_txt">1234567890</textarea>
            </div>
            <div class="panel-footer">
                <button class="btn" id="btn">go</button>
            </div>
        </div>


    </div>


    <script>

        function setSelectionRange(input, selectionStart, selectionEnd) {
            if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }
            else if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            }
        }

        function setCaretToPos(input, pos) {
            setSelectionRange(input, pos, pos);
        }

        setCaretToPos(document.getElementById("my_txt"), 5);



        $('#btn').click(function () {

            var txt_dom = document.getElementById("my_txt").value;

            var position = txt_dom.selectionStart;
            console.log("光标位置: " + position);

            var index = txt_dom.value.lastIndexOf(" ", position);
            console.log("光标前空格位置: " + index);


            var len = txt_dom.value.length;
            var charArr = txt_dom.value.toChart();
            document.getElementById("my_txt").value = document.getElementById("my_txt").value.slice(0, index) + document.getElementById("my_txt").value.slice(index, len);


        });





    </script>


</body>

</html>